package com.module.home.ui.home

import android.animation.Animator
import android.animation.Animator.AnimatorListener
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import com.airbnb.lottie.LottieDrawable
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.base.AppBackPressedFragment
import com.common.app.core.RouterHub
import com.common.app.data.bean.CommonMessageRelayModel
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.KeyPre
import com.common.app.data.bean.ServerSseDataModel
import com.common.app.data.bean.UpKvDataModel
import com.common.app.helper.EventUmengAgent
import com.common.app.helper.RouterHelper
import com.common.app.helper.UmengAgentHelper
import com.common.app.helper.UserHelper
import com.common.app.utls.BrotliCompressionEx.compressJsonByBrotli
import com.common.app.utls.TimeUtils
import com.common.app.utls.TimerUtils
import com.common.app.utls.report.ReportEventManager
import com.common.base.app.activity.BaseVMActivity
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.getShowMsg
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.post
import com.common.base.app.extras.postDelay
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.setVisibility
import com.common.base.app.extras.showToast
import com.common.base.app.extras.startActivity
import com.common.base.app.extras.yes
import com.common.base.utils.JsonUtils
import com.common.base.utils.MathUtil
import com.common.base.utils.SpUtilsManagement
import com.common.base.utils.SpanUtils
import com.common.base.utils.StatusBarUtils
import com.common.base.utils.ToastUtils
import com.common.base.utils.ViewUtils.getColor
import com.common.base.widget.animator.CustomAnimation1
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.data.bean.CusUnifyData
import com.module.ble.db.table.UserAcLevel
import com.module.ble.db.table.UserBloodOxygen
import com.module.ble.db.table.UserBodyTemperature
import com.module.ble.db.table.UserCalorie
import com.module.ble.db.table.UserHeartRate
import com.module.ble.db.table.UserHrv
import com.module.ble.db.table.UserRespiratoryRate
import com.module.ble.db.table.UserSleepInfo
import com.module.ble.db.table.UserSportRecord
import com.module.ble.db.table.UserStand
import com.module.ble.db.table.UserStepsRelatedRecord
import com.module.ble.db.table.UserStress
import com.module.ble.listener.CusSynthesisHealthExpandListener
import com.module.ble.listener.CusBleDeviceInfoExpandListener
import com.module.ble.listener.CusConnectBleDeviceExpandListener
import com.module.ble.repo.HeartRateRepo
import com.module.ble.repo.BloodOxygenRepo
import com.module.ble.repo.BodyTemperatureRepo
import com.module.ble.repo.HeartRateVariabilityRepo
import com.module.ble.repo.SleepInfoRepo
import com.module.ble.repo.SportRecordRepo
import com.module.ble.repo.UserStepsRelatedRecordRepo
import com.module.ble.repo.UserCalorieRepo
import com.module.ble.repo.UserStandRepo
import com.module.ble.repo.UserStressRepo
import com.module.ble.repo.RespiratoryRateRepo
import com.module.ble.repo.UserAcLevelRepo
import com.module.ble.utils.AizoSDKUtil
import com.module.ble.utils.AizoSDKUtil.connectBleAndInitDevice
import com.module.ble.utils.AizoSDKUtil.getBindRingInfo
import com.module.ble.utils.AizoSDKUtil.getBleBindingMac
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.utils.BleOtherUtil.convertBloodOxygen
import com.module.ble.utils.BleOtherUtil.convertToChartData
import com.module.ble.utils.BluetoothPairingUtil
import com.module.ble.utils.BluetoothPairingUtil.getCurrentBluetoothState
import com.module.ble.utils.CloudDataDecompressionV2Worker
import com.module.ble.utils.CloudDataDecompressionWorker
import com.module.ble.utils.CommonCusHealthType.HEARTRATE
import com.module.ble.utils.DeviceFirmType
import com.module.ble.utils.ServerHealthDataModelType
import com.module.ble.utils.SynRingAllDataWorker
import com.module.home.R
import com.module.home.databinding.HomeMainFragmentBinding
import com.module.home.databinding.HomeMainHeadCradViewBinding
import com.module.home.ui.scoringFactors.ScoringFactorsActivity
import com.module.home.utils.UploadStatistics
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Calendar
import java.util.concurrent.TimeUnit
import kotlin.random.Random


/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/10/12
 * <p>
 * 描述：首页模块主页
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_HOME_FRAGMENT)
class HomeMainFragment : AppBackPressedFragment<HomeMainFragmentBinding, HomeMainViewModel>(),
    CusConnectBleDeviceExpandListener, CusSynthesisHealthExpandListener,
    CusBleDeviceInfoExpandListener {

    private val classicsFooter by lazy { ClassicsFooter(requireActivity()) }

    override fun getViewBinding() = HomeMainFragmentBinding.inflate(layoutInflater)
    override fun getPlaceholderView() = mViewBinding.mPlaceholderView
    override fun getViewModel(): Class<HomeMainViewModel> = HomeMainViewModel::class.java

    private val headBingDing by lazy { HomeMainHeadCradViewBinding.inflate(layoutInflater) }

    private val cardAdapter by lazy { HomeMainCardAdapter() }

    var currentTime = TimeUtils.getTimeDateLong()

    // 添加上传统计实例
    private val uploadStatistics = UploadStatistics()

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewBinding.statusView)

        TimerUtils.addTimerKey(KeyEvents.KEY_TIME_30S_EVENT)

        //上下拉刷新
        getRefreshFooter()?.let { mViewBinding.pdView.setRefreshFooter(it) }
        mViewBinding.pdView.setRefreshHeader(
            ClassicsHeader(requireActivity())
                .setAccentColor(
                    ContextCompat.getColor(requireActivity(), R.color.white_80)
                )
        )
        classicsFooter.setAccentColor(
            ContextCompat.getColor(
                requireActivity(),
                R.color.color_999999
            )
        )
        mViewBinding.pdView.setRefreshFooter(classicsFooter)

//        if (!cardAdapter.animationEnable) {
//            cardAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn)
//            cardAdapter.isAnimationFirstOnly = false
//        }

        cardAdapter.apply {
            cardAdapter.addHeaderView(headBingDing.root)
            cardAdapter.addFooterView(layoutInflater.inflate(R.layout.base_rlv_margin_footer_tr_view150, null))
            adapterAnimation = CustomAnimation1()
            isAnimationFirstOnly = true
//            isAnimationFirstOnly = false
            mViewBinding.hrv.adapter = this
        }

        headBingDing.animScoreCardOpen.progress = 1f


        mViewModel.initFloatWindow(
            requireActivity(),
            1,
            "",
            this
        )

        createCloudDataDecompressionWorker()
    }

    override fun lazyInitData() {
        super.lazyInitData()

        checkBindingDevice()

        TimerUtils.startTimer()

        createPeriodicSynWork()

        getAllScoringFactors()
        getHomeAiNotifDetail()

        //测试用
////        HeartRateRepo.instance.deleteInvalidHeartRateData()
////        BloodOxygenRepo.instance.deleteInvalidBloodOxygenData()
//        UserStepsRelatedRecordRepo.instance.deleteInvalidStepsData()
////        SportRecordRepo.instance.deleteInvalidData()
//        HeartRateRepo.instance.updateAllSysStatToZero()
//        HeartRateVariabilityRepo.instance.updateAllSysStatToZero()
//        BloodOxygenRepo.instance.updateAllSysStatToZero()
//        BodyTemperatureRepo.instance.updateAllSysStatToZero()
//        UserCalorieRepo.instance.updateAllSysStatToZero()
//        SleepInfoRepo.instance.updateAllSysStatToZero()
//        SportRecordRepo.instance.updateAllSysStatToZero()
////        SleepInfoRepo.instance.updateSleepTypeToZeroForFirm1()
//        UserStepsRelatedRecordRepo.instance.updateAllSysStatToZero()
    }

    override fun initEvents() {
        super.initEvents()

        setErrorRetryListener {
        }

        // 开始监听蓝牙状态
        BluetoothPairingUtil.startBluetoothStateListener { isBluetoothEnabled ->
            if (isBluetoothEnabled) {
                Log.i("MainActivity", "蓝牙已开启")
                changeRingRelatedUi(1)
                AizoSDKUtil.curMac?.let { macIt ->
                  connectBleAndInitDevice(macIt, AizoSDKUtil.getRingFirm())
                }
            } else {
                Log.i("MainActivity", "蓝牙已关闭")
                changeRingRelatedUi(31)
            }
        }

        AizoSDKUtil.addSynthesisHealthExpandListener(this)
        AizoSDKUtil.addConnectBleDeviceExpandListener(this)
        AizoSDKUtil.addBleDeviceInfoExpandListener(this)

        headBingDing.animScoreCardOpen.addAnimatorListener(object : AnimatorListener {
            override fun onAnimationStart(p0: Animator) {
                Log.e("SOU---LottieAnimationView", "onAnimationStart:")
            }

            override fun onAnimationEnd(p0: Animator) {
                Log.e("SOU---LottieAnimationView", "onAnimationEnd:")
                headBingDing.animScoreCardOpen.removeAllAnimatorListeners()
            }

            override fun onAnimationCancel(p0: Animator) {
                Log.e("SOU---LottieAnimationView", "onAnimationCancel:")
                headBingDing.animScoreCardOpen.removeAllAnimatorListeners()
            }

            override fun onAnimationRepeat(p0: Animator) {
                Log.e("SOU---LottieAnimationView", "onAnimationRepeat:")
            }

        })
        headBingDing.animScoreCardOpen.addAnimatorPauseListener(object :
            Animator.AnimatorPauseListener {
            override fun onAnimationPause(p0: Animator) {
                Log.e("SOU---LottieAnimationView", "onAnimationPause:")
            }

            override fun onAnimationResume(p0: Animator) {
                Log.e("SOU---LottieAnimationView", "onAnimationResume:")
            }

        })

        headBingDing.tvToHealthDataDetails.setOnClickListener(onClick = object : View.OnClickListener {
            override fun onClick(p0: View?) {
                RouterHelper.navigationPostcard(RouterHub.ROUTER_HOME_SCORING_FACTORS)
                    .withInt(KeyBundle.BUNDLE_KEY, 0)
                    .withString(KeyBundle.EXPAND_DATA, TimeUtils.getYearMonthDay(currentTime))
                    .navigation()
            }
        })

        mViewModel.mPressureScore.observe(this) {
            SpanUtils.create()
                .addSection("  ${getString(R.string.common_pressure_hint)} $it")
                .showIn(headBingDing.tvPressure)
        }
        mViewModel.mSleepScore.observe(this) {
            SpanUtils.create()
                .addSection("${getString(R.string.common_sleep_hint)} $it")
                .showIn(headBingDing.tvSleep)
        }
        mViewModel.mExerciseScore.observe(this) {
            SpanUtils.create()
                .addSection("${getString(R.string.common_exercise_hint)} $it")
                .showIn(headBingDing.tvExercise)
        }
        mViewModel.mSignsScore.observe(this) {
            SpanUtils.create()
                .addSection("${getString(R.string.common_signs_hint)} $it")
                .showIn(headBingDing.tvSigns)
        }

//        mViewModel.scoreColor1.observe(this) {
//            ValueAnimator.ofFloat(0f, it ?: 0f)
//                .setDuration(330)
//                .apply {
//                    addUpdateListener { animation ->
//                        mViewBinding.animScoreColor1.progress =
//                            animation.animatedValue as Float
//                    }
//                    start()
//                }
//        }
//        mViewModel.scoreColor2.observe(this) {
//            ValueAnimator.ofFloat(0f, it ?: 0f)
//                .setDuration(363)
//                .apply {
//                    addUpdateListener { animation ->
//                        mViewBinding.animScoreColor2.progress =
//                            animation.animatedValue as Float
//                    }
//                    start()
//                }
//        }
//        mViewModel.scoreColor3.observe(this) {
//            ValueAnimator.ofFloat(0f, it ?: 0f)
//                .setDuration(396)
//                .apply {
//                    addUpdateListener { animation ->
//                        mViewBinding.animScoreColor3.progress =
//                            animation.animatedValue as Float
//                    }
//                    start()
//                }
//        }
//        mViewModel.scoreColor4.observe(this) {
//            ValueAnimator.ofFloat(0f, it ?: 0f)
//                .setDuration(429)
//                .apply {
//                    addUpdateListener { animation ->
//                        mViewBinding.animScoreColor4.progress =
//                            animation.animatedValue as Float
//                    }
//                    start()
//                }
//        }

        mViewBinding.pdView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                mViewBinding.pdView.finishLoadMore()
                mViewBinding.pdView.finishLoadMoreWithNoMoreData()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                AizoSDKUtil.curMac?.let { macIt ->
                    AizoSDKUtil.isConnect().no {
                        connectBleAndInitDevice(macIt, AizoSDKUtil.getRingFirm())
                    }
                }
                mViewModel.refreshDBAllData()
                AizoSDKUtil.getDevicePowerState()
                getOneDayAllData()
                AizoSDKUtil.getSynMultiDaysHr(14)
                findAllClassData()
////                currentTime = arrayOf(1748394000000, 1748405520000, 1748420400000).random()//测试效果
//                currentTime = TimeUtils.getTimeDateLong()
//                addTestCardData()

                getAllScoringFactors()
                getHomeAiNotifDetail()

//                mViewModel.reconnectSse()//下载云端数据

            }
        })

        LiveEventBus.get(KeyEvents.KEY_TIME_EVENT).observe(this) {
            val value = TimerUtils.getTimerStep(KeyEvents.KEY_TIME_30S_EVENT)
            if (value != -1 && value % 10 == 0 && isVisible) {//断连时每10秒执行一次重连
//                AizoSDKUtil.curMac?.let { macIt ->
//                    AizoSDKUtil.isConnect().no {
//                        connectBleDevice(macIt, AizoSDKUtil.getRingFirm())
//                    }
//                }
            }
            if (value != -1 && value % 60 == 0) {//每60秒执行一次
                AizoSDKUtil.curMac?.let { macIt ->
                    if (isSupportVisible && AizoSDKUtil.isConnect()) {
//                    AizoSDKUtil.curElectricity.isNullOrEmpty().yes {AizoSDKUtil.getDevicePowerState()}
                        AizoSDKUtil.getDevicePowerState()
                    }
                }
            }
            (value != -1 && value % (3 * 60) == 0).yes {//每3分钟执行一次
                if (AizoSDKUtil.isConnect()) {
                    getOneDayAllData()
                }
            }
            (value != -1 && value % (30 * 60) == 0).yes {//每30分钟执行一次
                findAllClassData()
            }
        }

        LiveEventBus.get(KeyEvents.KEY_HOME_UP_STATS_COMPLETED).observe(this){
            uploadSyncFinished()
        }

        mViewBinding.tvToBinding.setOnClickListener(onClick = this)
        headBingDing.animScoreTotalCard.setOnClickListener(onClick = this)

        headBingDing.vClickAnimScore1.setOnClickListener(onClick = this)
        headBingDing.vClickAnimScore2.setOnClickListener(onClick = this)
        headBingDing.vClickAnimScore3.setOnClickListener(onClick = this)
        headBingDing.vClickAnimScore4.setOnClickListener(onClick = this)

//        cardAdapter.setOnItemClickListener(object : OnItemClickListener {
//            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
//                if ((adapter.data[position] as HomeMainCardModel).getItemType() == 10086) return
//                RouterHelper.navigationPostcard(RouterHub.ROUTER_AICHAT_CHAT_MAIN)
//                    .withInt(
//                        KeyBundle.BUNDLE_KEY,
//                        (adapter.data[position] as HomeMainCardModel).id.toInt()
//                    )
////                    .withString(
////                        KeyBundle.EXPAND_DATA,
////                        (adapter.data[position] as HomeMainCardModel).text
////                    )
//                    .navigation()
//            }
//        })
//        cardAdapter.setOnItemChildClickListener(object : OnItemChildClickListener {
//            override fun onItemChildClick(
//                adapter: BaseQuickAdapter<*, *>,
//                view: View,
//                position: Int
//            ) {
//                when (view.id) {
//                    R.id.tvAiSuggestion->{
//                        RouterHelper.navigationPostcard(RouterHub.ROUTER_AICHAT_CHAT_MAIN)
//                            .withInt(
//                                KeyBundle.BUNDLE_KEY,
//                                cardAdapter.data[position].id
//                            )
//                    .withString(
//                        KeyBundle.EXPAND_DATA,
//                        cardAdapter.data[position].ai_analyze_result?.affirmation
//                    )
//                            .navigation()
//                    }
//                }
//            }
//        })

        LiveEventBus.get(KeyEvents.KEY_HOME_SCENE_MODE_CONFIG, CommonMessageRelayModel::class.java).observe(this) {
            it?.let { beanIt->
                RouterHelper.navigationPostcard(RouterHub.ROUTER_AICHAT_CHAT_MAIN)
                    .withInt(KeyBundle.BUNDLE_KEY, beanIt.webType)
                    .withString(KeyBundle.EXPAND_DATA, beanIt.skipPath)
                    .navigation()
            }
        }

        //浮窗点击事件
        mViewModel.floatingViewClick.observe(this)
        {
            RouterHelper.navigation(RouterHub.ROUTER_AICHAT_CHAT_MAIN)
        }

        mViewModel._sseData.observe(this) { sseDataIt ->
            JsonUtils.fromJson(sseDataIt, ServerSseDataModel::class.java)?.apply {

                (100 <= this.progress ).yes {
                    mViewModel.stopSse()
                    createCloudDataDecompressionWorker()
                }

                this.data.isNullOrEmpty().no {
                    this.data?.forEach {
                        it.userId = UserHelper.getUserDbName()
                    }

                    ReportEventManager.saveCloudDownData(this.data)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        checkBindingDevice()
    }

    override fun onDestroy() {
        AizoSDKUtil.removeConnectBleDeviceExpandListener(this)
        AizoSDKUtil.removeSynthesisHealthExpandListener(this)
        AizoSDKUtil.removeBleDeviceInfoExpandListener(this)
        TimerUtils.cancelTimer()
        mViewModel.stopSse()
        super.onDestroy()
    }

    override fun onSupportVisible() {
        super.onSupportVisible()
        StatusBarUtils.setStatusBarForegroundColor(activity, true)
        UmengAgentHelper.onEvent(EventUmengAgent.visit_home_main)
        currentTime = TimeUtils.getTimeDateLong()
        mViewModel.showFloatWindow()
//        addTestCardData()
    }

    override fun onSupportInvisible() {
        super.onSupportInvisible()
        mViewModel.hideFloatWindow()
    }

    override fun showErrorToast(msg: String?) {
        super.showErrorToast(msg)
        ToastUtils.showToast(msg)
    }

    override fun onClick(v: View?) {
        when (v) {
            mViewBinding.tvToBinding -> RouterHelper.navigation(RouterHub.ROUTER_BIND_GUIDE)
            headBingDing.animScoreTotalCard -> {
//                showToast("待开发！")
            }
            headBingDing.vClickAnimScore1 -> {
                val bundle = Bundle()
                bundle.putInt(KeyBundle.BUNDLE_KEY, 0)
                bundle.putString(KeyBundle.EXPAND_DATA, TimeUtils.getYearMonthDay(currentTime))
                requireActivity().startActivity<ScoringFactorsActivity>(bundle, false)
            }
            headBingDing.vClickAnimScore2 -> {
                val bundle = Bundle()
                bundle.putInt(KeyBundle.BUNDLE_KEY, 1)
                bundle.putString(KeyBundle.EXPAND_DATA, TimeUtils.getYearMonthDay(currentTime))
                requireActivity().startActivity<ScoringFactorsActivity>(bundle, false)

            }
            headBingDing.vClickAnimScore3 -> {
                val bundle = Bundle()
                bundle.putInt(KeyBundle.BUNDLE_KEY, 2)
                bundle.putString(KeyBundle.EXPAND_DATA, TimeUtils.getYearMonthDay(currentTime))
                requireActivity().startActivity<ScoringFactorsActivity>(bundle, false)

            }
            headBingDing.vClickAnimScore4 -> {
                val bundle = Bundle()
                bundle.putInt(KeyBundle.BUNDLE_KEY, 3)
                bundle.putString(KeyBundle.EXPAND_DATA, TimeUtils.getYearMonthDay(currentTime))
                requireActivity().startActivity<ScoringFactorsActivity>(bundle, false)
            }
        }
    }

    fun bgZoomAnimation() {

        //缩放四叶草背景
        ValueAnimator.ofFloat(1f, 0f)
            .apply {
                addListener(object : AnimatorListener {
                    override fun onAnimationStart(p0: Animator) {
                        Log.e("SOU---ValueAnimator", "onAnimationRepeat:")
                    }

                    override fun onAnimationEnd(p0: Animator) {
                        Log.e("SOU---ValueAnimator", "onAnimationRepeat:")
                        headBingDing.animScoreCardOpen.progress = 0f
                        headBingDing.animScoreCardOpen.resumeAnimation()
                    }

                    override fun onAnimationCancel(p0: Animator) {
                        Log.e("SOU---ValueAnimator", "onAnimationRepeat:")
                    }

                    override fun onAnimationRepeat(p0: Animator) {
                        Log.e("SOU---ValueAnimator", "onAnimationRepeat:")
                    }

                })
                addUpdateListener { animation ->
                    headBingDing.animScoreCardOpen.progress =
                        animation.animatedValue as Float
                }
                start()
            }
    }

    /**
     * 自定义播放动画和时长
     */
    private fun playValueAnimator() {
        //缩放四叶草背景
        bgZoomAnimation()

        postDelay(200) {
            ValueAnimator.ofFloat(0f, mViewModel.scoreColor1 ?: 0f)
                .setDuration(330)
                .apply {
                    addUpdateListener { animation ->
                        headBingDing.animScoreColor1.progress =
                            animation.animatedValue as Float
                    }
                    start()
                }
            ValueAnimator.ofFloat(0f, mViewModel.scoreColor2 ?: 0f)
                .setDuration(363)
                .apply {
                    addUpdateListener { animation ->
                        headBingDing.animScoreColor2.progress =
                            animation.animatedValue as Float
                    }
                    start()
                }
            ValueAnimator.ofFloat(0f, mViewModel.scoreColor3 ?: 0f)
                .setDuration(396)
                .apply {
                    addUpdateListener { animation ->
                        headBingDing.animScoreColor3.progress =
                            animation.animatedValue as Float
                    }
                    start()
                }
            ValueAnimator.ofFloat(0f, mViewModel.scoreColor4 ?: 0f)
                .setDuration(429)
                .apply {
                    addUpdateListener { animation ->
                        headBingDing.animScoreColor4.progress =
                            animation.animatedValue as Float
                    }
                    start()
                }
        }

    }

    /**
     * 设置幸运草卡片的底部展示数据
     */
    private fun setScoreCardOtherValue() {
        headBingDing.tvPressure.text = "${getString(R.string.common_pressure_hint)} ${
            MathUtil.mulInt(
                mViewModel.scoreColor1,
                100
            )
        }"
        headBingDing.tvSleep.text = "${getString(R.string.common_sleep_hint)} ${
            MathUtil.mulInt(
                mViewModel.scoreColor2,
                100
            )
        }"
        headBingDing.tvExercise.text = "${getString(R.string.common_exercise_hint)} ${
            MathUtil.mulInt(
                mViewModel.scoreColor3,
                100
            )
        }"
        headBingDing.tvSigns.text = "${getString(R.string.common_signs_hint)} ${
            MathUtil.mulInt(
                mViewModel.scoreColor4,
                100
            )
        }"
    }

    fun findAllClassData() {
        // 开始新的统计会话
        val sessionId = uploadStatistics.startNewSession()
        Log.i("HomeMainFragment", "开始执行 findAllClassData，统计会话: $sessionId")

        // 使用协程在后台线程执行数据库操作
        CoroutineScope(Dispatchers.IO).launch {
            // 先统计有多少种数据类型需要检查
            var expectedRequests = 0

            // 检查每种数据类型是否有待上传数据
            HeartRateRepo.instance.findAllNotUp()?.let { if (it.isNotEmpty()) expectedRequests++ }
            HeartRateVariabilityRepo.instance.findAllNotUp()?.let { if (it.isNotEmpty()) expectedRequests++ }
            BloodOxygenRepo.instance.findAllNotUp()?.let { if (it.isNotEmpty()) expectedRequests++ }
            BodyTemperatureRepo.instance.findAllNotUp()?.let { if (it.isNotEmpty()) expectedRequests++ }
            UserCalorieRepo.instance.findAllNotUp()?.let { if (it.isNotEmpty()) expectedRequests++ }
            SleepInfoRepo.instance.findAllNotUp()?.let { if (it.isNotEmpty()) expectedRequests++ }
            SportRecordRepo.instance.findAllNotUp()?.let { if (it.isNotEmpty()) expectedRequests++ }
            UserStepsRelatedRecordRepo.instance.findAllNotUp()?.let { if (it.isNotEmpty()) expectedRequests++ }
            UserStressRepo.instance.findAllNotUp()?.let { if (it.isNotEmpty()) expectedRequests++ }
            UserStandRepo.instance.findAllNotUp()?.let { if (it.isNotEmpty()) expectedRequests++ }
            RespiratoryRateRepo.instance.findAllNotUp()?.let { if (it.isNotEmpty()) expectedRequests++ }
            UserAcLevelRepo.instance.findAllNotUp()?.let { if (it.isNotEmpty()) expectedRequests++ }

            // 设置预期请求数量
            CoroutineScope(Dispatchers.Main).launch {
                uploadStatistics.setExpectedRequestCount(expectedRequests)
            }

            // 如果没有待上传数据，直接完成统计
            if (expectedRequests == 0) {
                CoroutineScope(Dispatchers.Main).launch {
                    Log.i("UploadStats", "本次 findAllClassData 执行完成，无待上传数据")
                }
                return@launch
            }

            // 执行实际的数据查找和上传
            findNotUpHrData()
            findNotUpHrvData()
            findNotUpOxyData()
            findNotUpTempData()
            findNotUpCalorieData()
            findNotUpSleepData()
            findNotUpSportData()
            findNotUpStepData()
            findNotUpStressData()
            findNotUpStandData()
            findNotUpBreathData()
            findNotUpAcLevelData()
        }
    }

    // 查找待上传心率数据
    private fun findNotUpHrData() {
//        HeartRateRepo.instance.findAll()?.let { listIt ->
        HeartRateRepo.instance.findAllNotUp()?.let { listIt ->
//        HeartRateRepo.instance.findByOneDay(TimeUtils.getTimeDateLong())?.let { listIt->
            upAllData(listIt, ServerHealthDataModelType.HEARTRATE.value)
        }
    }

    // 查找待上传心率变异性数据
    private fun findNotUpHrvData() {
        HeartRateVariabilityRepo.instance.findAllNotUp()?.let { listIt ->
            upAllData(listIt, ServerHealthDataModelType.HRV.value)
        }
    }

    // 查找待上传血氧数据
    private fun findNotUpOxyData() {
        BloodOxygenRepo.instance.findAllNotUp()?.let { listIt ->
            upAllData(listIt, ServerHealthDataModelType.BLOODOXYGEN.value)
        }
    }

    // 查找待上传体温数据
    private fun findNotUpTempData() {
        BodyTemperatureRepo.instance.findAllNotUp()?.let { listIt ->
            upAllData(listIt, ServerHealthDataModelType.BODYTEMP.value)
        }
    }

    // 查找待上传卡路里数据
    private fun findNotUpCalorieData() {
        UserCalorieRepo.instance.findAllNotUp()?.let { listIt ->
            upAllData(listIt, ServerHealthDataModelType.CALORIE.value)
        }
    }

    // 查找待上传睡眠数据
    private fun findNotUpSleepData() {

//        SleepInfoRepo.instance.findAll()?.let { listIt ->
        SleepInfoRepo.instance.findAllNotUp()?.let { listIt ->
//            val asa = JsonUtils.toJson(listIt)
            upAllData(listIt, ServerHealthDataModelType.SLEEP.value)
        }
    }

    // 查找待上传运动数据
    private fun findNotUpSportData() {
        SportRecordRepo.instance.findAllNotUp()?.let { listIt ->
            upAllData(listIt, ServerHealthDataModelType.EXERCISE.value)
        }
    }

    // 查找待上传步数数据
    private fun findNotUpStepData() {
        UserStepsRelatedRecordRepo.instance.findAllNotUp()?.let { listIt ->
            upAllData(listIt, ServerHealthDataModelType.STEPS.value)
        }
    }


    // 查找待上传压力数据
    private fun findNotUpStressData() {
        UserStressRepo.instance.findAllNotUp()?.let { listIt ->
            upAllData(listIt, ServerHealthDataModelType.STRESS.value)
        }
    }

    // 查找待上传站立数据
    private fun findNotUpStandData() {
        UserStandRepo.instance.findAllNotUp()?.let { listIt ->
            upAllData(listIt, ServerHealthDataModelType.STAND.value)
        }
    }

    // 查找待上传呼吸率数据
    private fun findNotUpBreathData() {
        RespiratoryRateRepo.instance.findAllNotUp()?.let { listIt ->
            upAllData(listIt, ServerHealthDataModelType.BREATH.value)
        }
    }

    // 查找待上传活动强度数据
    private fun findNotUpAcLevelData() {
        UserAcLevelRepo.instance.findAllNotUp()?.let { listIt ->
            upAllData(listIt, ServerHealthDataModelType.ACLEVEL.value)
        }
    }

    // 上传数据
    private fun upAllData(mDataList: List<CusUnifyData>, mType: String) {
        if (mDataList.isNullOrEmpty()) return

        val tempList = mutableListOf<UpKvDataModel>()
        mDataList.forEach { beanIt ->
            tempList.add(
                UpKvDataModel(
                    beanIt.createdTime.toString(),
                    JsonUtils.toJson(beanIt)
                )
            )
        }

        tempList.sortByDescending { it.timestamp }//降序

        val compressJsonTemp = compressJsonByBrotli(JsonUtils.toJson(tempList))

        // 生成请求ID并添加到统计
        val requestId = "${mType}_${System.currentTimeMillis()}"
        uploadStatistics.addRequest(requestId, mType, tempList.size)

        CoroutineScope(Dispatchers.Main).launch {
            mViewModel.uploadHrData(
                mDataList,
                tempList.firstOrNull()?.timestamp.toString(),
                tempList.lastOrNull()?.timestamp.toString(),
                mType,
                tempList.size.toString(),
                getBindRingInfo()?.version ?: "",
                getBleBindingMac() ?: "",
                AizoSDKUtil.getCurRingFirm(),
                compressJsonTemp
            ).observe(this@HomeMainFragment) { responseIt ->
                // 标记请求完成状态
                val isSuccess = responseIt.isSuccess()
                uploadStatistics.markCompleted(requestId, isSuccess)

                responseIt.isSuccess().yes {
                    doOnIOThread {
                        val uploadResult = responseIt.Data
                        val serverResponse = uploadResult?.serverResponse
                        Log.e(BaseVMActivity.TAG, "YQ: uploadCompressedData-------decompressedJson： $responseIt")

                        uploadResult?.originalData?.let { originalDataIt ->
                            try {
                                // 尝试将所有元素转换为SyncableData
                                val syncableDataList = originalDataIt.mapNotNull { item ->
                                    when (item) {
                                        is CusUnifyData -> item
                                        else -> {
                                            Log.w(
                                                BaseVMActivity.TAG,
                                                "YQ: Unexpected data type: ${item::class.java.simpleName}"
                                            )
                                            null
                                        }
                                    }
                                }

                                syncableDataList.isNotEmpty().yes {
                                    syncableDataList.forEach { it.sysStat = 1 }

                                    // 分别处理不同类型的数据
                                    val heartRateList = syncableDataList.filterIsInstance<UserHeartRate>()
                                    heartRateList.isNotEmpty().yes {
                                        val heartRateListTemp = heartRateList.filter { it.heartRate > 0 } // 过滤掉pace为0的数据
                                        HeartRateRepo.instance.updateBatch(heartRateListTemp)
                                        Log.e(BaseVMActivity.TAG, "YQ: heartRate originalUpList size: ${heartRateList.size}")
                                    }
                                    val hrvList = syncableDataList.filterIsInstance<UserHrv>()
                                    hrvList.isNotEmpty().yes {
//                                        val hrvListTemp = hrvList.filter { it.heartRateVariability > 0 } // 过滤掉pace为0的数据
                                        HeartRateVariabilityRepo.instance.updateBatch(hrvList)
                                        Log.e(BaseVMActivity.TAG, "YQ: hrvList originalUpList size: ${hrvList.size}")
                                    }

                                    val bloodOxygenList = syncableDataList.filterIsInstance<UserBloodOxygen>()
                                    bloodOxygenList.isNotEmpty().yes {
                                        val bloodOxygenListTemp = bloodOxygenList.filter { it.bloodOxygen > 0 } // 过滤掉pace为0的数据
                                        BloodOxygenRepo.instance.updateBatch(bloodOxygenListTemp)
                                        Log.e(BaseVMActivity.TAG, "YQ: bloodOxygenList originalUpList size: ${bloodOxygenList.size}")
                                    }

                                    val temList = syncableDataList.filterIsInstance<UserBodyTemperature>()
                                    temList.isNotEmpty().yes {
                                        val bodyTempListTemp = temList.filter { it.bodyTemperature > 0 } // 过滤掉pace为0的数据
                                        BodyTemperatureRepo.instance.updateBatch(bodyTempListTemp)
                                        Log.e(BaseVMActivity.TAG, "YQ: temList originalUpList size: ${temList.size}")
                                    }

                                    val calorieList = syncableDataList.filterIsInstance<UserCalorie>()
                                    calorieList.isNotEmpty().yes {
                                        UserCalorieRepo.instance.updateBatch(calorieList)
                                        Log.e(BaseVMActivity.TAG, "YQ: calorieList originalUpList size: ${calorieList.size}")
                                    }

                                    val sleepList = syncableDataList.filterIsInstance<UserSleepInfo>()
                                    sleepList.isNotEmpty().yes {
                                        val sleepTempListTemp = sleepList.filter { it.sleepQuality > -2 } // 过滤掉pace为空的数据
                                        SleepInfoRepo.instance.updateBatch(sleepTempListTemp)
                                        Log.e(BaseVMActivity.TAG, "YQ: sleepList originalUpList size: ${sleepList.size}")
                                    }

                                    val sportList = syncableDataList.filterIsInstance<UserSportRecord>()
                                    sportList.isNotEmpty().yes {
                                        val sportTempListTemp = sportList.filter { it.sportType > -2 } // 过滤掉pace为空的数据
                                        SportRecordRepo.instance.updateBatch(sportTempListTemp)
                                        Log.e(BaseVMActivity.TAG, "YQ: sportList originalUpList size: ${sportList.size}")
                                    }

                                    val stepList = syncableDataList.filterIsInstance<UserStepsRelatedRecord>()
                                    stepList.isNotEmpty().yes {
                                        UserStepsRelatedRecordRepo.instance.updateBatch(stepList)
                                        Log.e(BaseVMActivity.TAG, "YQ: stepList originalUpList size: ${stepList.size}")
                                    }

                                    val stressList = syncableDataList.filterIsInstance<UserStress>()
                                    stressList.isNotEmpty().yes {
                                        UserStressRepo.instance.updateBatch(stressList)
                                        Log.e(BaseVMActivity.TAG, "YQ: stressList originalUpList size: ${stressList.size}")
                                    }

                                    val standList = syncableDataList.filterIsInstance<UserStand>()
                                    stepList.isNotEmpty().yes {
                                        UserStandRepo.instance.updateBatch(standList)
                                        Log.e(BaseVMActivity.TAG, "YQ: standList originalUpList size: ${standList.size}")
                                    }

                                    val breathList = syncableDataList.filterIsInstance<UserRespiratoryRate>()
                                    breathList.isNotEmpty().yes {
                                        RespiratoryRateRepo.instance.updateBatch(breathList)
                                        Log.e(BaseVMActivity.TAG, "YQ: breathList originalUpList size: ${breathList.size}")
                                    }

                                    val acLevelList = syncableDataList.filterIsInstance<UserAcLevel>()
                                    acLevelList.isNotEmpty().yes {
                                        UserAcLevelRepo.instance.updateBatch(acLevelList)
                                        Log.e(BaseVMActivity.TAG, "YQ: acLevelList originalUpList size: ${acLevelList.size}")
                                    }
                                }
                            } catch (e: Exception) {
                                Log.e(BaseVMActivity.TAG, "YQ: Error processing originalData", e)
                            }
                        }
                    }
                }.otherwise {
                    // 错误处理
                    Log.e(BaseVMActivity.TAG, "mViewModel.uploadHrData： $responseIt")
                }
            }
        }

    }

    private fun finishPdView() {
        mViewBinding.pdView.finishRefresh()
        mViewBinding.pdView.finishLoadMore()
        mViewBinding.pdView.setNoMoreData(true)
    }

    private fun checkBindingDevice() {
        SpUtilsManagement.getString(KeyPre.KEY_RING_MAC, "").isNullOrEmpty().run {
            setVisibility(mViewBinding.addRing, this)
            changeRingRelatedUi(if (this) -1 else (if (AizoSDKUtil.isConnect()) 2 else 1))

//            mViewBinding.tvRingInfoLL.visibility = if(this) View.INVISIBLE else View.VISIBLE
        }
    }

    private fun toCheckPage(mType: Int = HEARTRATE.value) {
        RouterHelper.navigationPostcard(RouterHub.ROUTER_HEALTH_CHECK)
            .withInt(KeyBundle.BUNDLE_KEY, mType)
            .navigation()
    }

    private fun getOneDayAllData(delayTime: Long = -1) {
        Log.i("TAG", "YQ-HDU: getOneDayAllData")
        AizoSDKUtil.getToDaysHr(delayTime)

    }

    private fun createOneTimeSynWork(delayTime: Long = -1) {
        Log.i("TAG", "YQ-HDU: createOneTimeSynWork")
        getOneDayAllData(delayTime)

        val workManager = WorkManager.getInstance(requireActivity())
        val workName = "SynRingAllDataImmediate"

        // 同步获取工作信息检查周期性工作是否已存在
        val workInfos = workManager.getWorkInfosForUniqueWork(workName).get()

        // 存在活跃工作则直接返回
        if (workInfos.any { it.state == WorkInfo.State.RUNNING }) {
            Log.d("WorkCheck", "任务已存在，无需创建")
            return
        }

        // 创建一次性工作请求（立即执行）
        val immediateWorkRequest = OneTimeWorkRequestBuilder<SynRingAllDataWorker>()
            .build()

        // 执行一次性工作
        workManager.enqueueUniqueWork(
            workName,
            ExistingWorkPolicy.REPLACE,
            immediateWorkRequest
        )
    }

    private fun createCloudDataDecompressionWorker() {

        val workManager = WorkManager.getInstance(requireActivity())
        val workName = "cloud_data_decompression"
        // 创建一次性云端数据解密工作请求（使用新Worker）
//        val request = OneTimeWorkRequestBuilder<CloudDataDecompressionWorker>()
        val request = OneTimeWorkRequestBuilder<CloudDataDecompressionV2Worker>()
            .build()

        // 唯一任务模式：若已存在则保持，不重复创建
        workManager.enqueueUniqueWork(
            workName,
            ExistingWorkPolicy.KEEP,
            request
        )
    }

    private fun createPeriodicSynWork() {

        val workManager = WorkManager.getInstance(requireActivity())
        val workName = "SynRingAllData"

        // 同步获取工作信息检查周期性工作是否已存在
        val workInfos = workManager.getWorkInfosForUniqueWork(workName).get()

        // 存在活跃工作则直接返回
        if (workInfos.any { it.state == WorkInfo.State.RUNNING }) {
            Log.d("WorkCheck", "任务已存在，无需创建")
            return
        }

        // 创建周期性工作请求
        val workRequest = PeriodicWorkRequestBuilder<SynRingAllDataWorker>(
            25, TimeUnit.MINUTES,  // 重复间隔
            5, TimeUnit.MINUTES    // 灵活时间窗口
        )
//            .setConstraints(//约束条件
//            Constraints.Builder()
//                .setRequiredNetworkType(NetworkType.CONNECTED)
//                .setRequiresBatteryNotLow(true)
//                .build())
            .build()

        // 执行周期性工作
        workManager.enqueueUniquePeriodicWork(
            workName,
            ExistingPeriodicWorkPolicy.REPLACE,
            workRequest
        )
    }

    private fun changeRingRelatedUi(mType: Int) {//-1未绑定设备0已断开1连接中2已连接11充电中21同步31蓝牙已关闭32蓝牙已开启
//        mViewBinding.animRingRelated.setImageAssetsFolder("images") //设置data.json引用的图片资源文件夹名称,如果没有可不写
        getCurrentBluetoothState().yes {
            headBingDing.animRingRelated.setAnimation(
                when (mType) {
                    -1 -> "home_anim_ring_unbound.json"
                    1 -> "home_anim_ring_connecting.json"
                    11 -> "home_anim_ring_power.json"
                    21 -> "home_anim_ring_update.json"
                    else -> {
                        AizoSDKUtil.curElectricity.isNullOrEmpty().no {
                            (30 >= AizoSDKUtil.curElectricity.toInt()).yes {//低电量
                                "home_anim_ring_low_default.json"
                            }.otherwise {
                                "home_anim_ring_default.json"
                            }
                        }.otherwise {
                            "home_anim_ring_default.json"
                        }
                    }
                }
            ) //通过AE生成的图文件(json格式)
        }.otherwise {
            headBingDing.animRingRelated.setAnimation("home_anim_ring_bluetooth_close.json") //31蓝牙已关闭
        }
//        headBingDing.animRingRelated.loop(true) //设置循环动画
        // 设置动画重复播放次数
        headBingDing.animRingRelated.setRepeatCount(ValueAnimator.INFINITE)
        // 设置动画重复播放模式为REVERSE
        headBingDing.animRingRelated.setRepeatMode(LottieDrawable.RESTART)

        headBingDing.animRingRelated.playAnimation() //开始动画
    }

    fun getHomeAiNotifDetail(){
        showDialogLoading()
        mViewModel.getHomeAiNotifDetail {
//            ToastUtils.showToast(it.getShowMsg())
            finishPdView()
        }.observe(this) {
                finishPdView()
                dismissLoadingDialog()
                it.isSuccess().yes {
                    it.isSuccess().yes {
                        it.Data?.let{ dataIt->
                            try {
                                cardAdapter.setList(dataIt)
                            } catch (e: Exception) {
                            }
                        }
                    }.otherwise {
                        showToast(it.Message)
                    }
                }.otherwise {
                    showToast(it.Message)
                }
            }
    }

    private fun getAllScoringFactors() {
        showDialogLoading()

        mViewModel.getAllScoringFactors(TimeUtils.getYearMonthDay(TimeUtils.getTimeDateLong())) {
            dismissLoadingDialog()
            finishPdView()
            showToast(it.getShowMsg())
        }.observe(this) {
            finishPdView()
            dismissLoadingDialog()
            it.isSuccess().yes {
                it.isSuccess().yes {
                    it.Data?.let { dataIt ->
                        dataIt.list?.forEach {listIt->

                            when(listIt.analysis_type){
                                "stress"->{
                                    mViewModel.scoreColor1 = MathUtil.div3(listIt.total_score.toString(),"100").toFloat()
                                }
                                "sleep"->{
                                    mViewModel.scoreColor2 =  MathUtil.div3(listIt.total_score.toString(),"100").toFloat()
                                }
                                "activity"->{
                                    mViewModel.scoreColor3 = MathUtil.div3(listIt.total_score.toString(),"100").toFloat()
                                }
                                "vital_sign"->{
                                    mViewModel.scoreColor4 = MathUtil.div3(listIt.total_score.toString(),"100").toFloat()
                                }
                                else->{

                                }
                            }
                        }

                        playValueAnimator()
                        SpanUtils.create()
                            .addSection(if (dataIt.total_grade.isNullOrBlank()) "" else "${dataIt.total_grade}\n")
                            .addForeColorSection(
                                dataIt.total_score.toString(),
                                getColor(R.color.c_017270)
                            )
                            .setAbsSize(dataIt.total_score.toString(), 20)
                            .setStyle(dataIt.total_score.toString(), Typeface.BOLD)
                            .addForeColorSection(
                                "  ${getString(R.string.common_score_hint)}",
                                getColor(R.color.c_017270)
                            )
                            .showIn(headBingDing.tvBodyBalance)

                        setScoreCardOtherValue()
                    }
                }.otherwise {
                    showToast(it.Message)
                }
            }.otherwise {
                showToast(it.Message)
            }
        }
    }

    private fun uploadSyncFinished() {
        mViewModel.uploadSyncFinished {
        }.observe(this) {
            it.isSuccess().yes {
                postDelay(30000){//30秒后执行一次评分查询
                    getHomeAiNotifDetail()
                }
            }
        }
    }

    @SuppressLint("MissingPermission")
    override fun onConnect(macStr: String?) {
        mViewModel.mDeviceConnectionFirst.yes {
            mViewModel.mDeviceConnectionFirst = false
            macStr?.let {
                BluetoothPairingUtil.isDevicePaired(it).no {
////                    BluetoothPairingUtil.pairDeviceNew(it) { success ->
////                        if (success) {
////                            Log.i("TAG", "YQ: Device paired successfully")
////                        } else {
////                            Log.i("TAG", "YQ: Failed to pair device")
////                        }
////                    }
//                    // 无感配对（不需要PIN码的设备）
//                    BluetoothPairingUtil.pairDeviceSilently(it) { success ->
//                        if (success) {
//                            Log.i("TAG", "Silent pairing successful")
//                        } else {
//                            Log.i("TAG", "Silent pairing failed")
//                        }
//                    }
                }
            }

            createOneTimeSynWork(2000)
        }

        changeRingRelatedUi(2)
        finishPdView()
    }

    override fun onConnectError(macStr: String?, throwable: Throwable?, state: Int) {
        changeRingRelatedUi(1)
        finishPdView()
    }

    override fun onDisconnect(macStr: String?) {
        changeRingRelatedUi(1)
        finishPdView()
    }

    override fun onHandleDevice(type: Int, result: Boolean) {
        when (type) {
//            2 -> changeMeasureUi(false)
            else -> {}
        }

        result.yes {
            dismissLoadingDialog()
            checkBindingDevice()
        }

        changeRingRelatedUi(-1)
    }

    override fun onBoundDeviceResult(macStr: String, result: Boolean) {
    }


    override fun onMeasureResult(
        result: Boolean,
        type: Int,
        time: Long,
        heartRate: Int,
        bloodOxygen: Int,
        bodyTemp: Float,
        envTemp: Float
    ) {
    }

    override fun onLatestHr(value: Int, macStr: String, time: Long) {
    }

    override fun onHeartRateDataListResult(result: List<UserHeartRate>) {
    }

    override fun getLatestBloodOxygen(value: Int, macStr: String, time: Long) {
    }

    override fun onBloodOxygenDataListResult(result: List<UserBloodOxygen>) {
    }

    override fun onLatestBodyTemper(value: Float, macStr: String, time: Long) {
    }

    override fun onBodyTemperDataListResult(result: List<UserBodyTemperature>) {
    }

    override fun onDevicePowerState(electricity: String, workingMode: Int) {//0未充电1充电中other未充电
        changeRingRelatedUi(if (workingMode == 1) 11 else AizoSDKUtil.isConnect)
    }

    override fun onGetDeviceInfo() {
    }
}